package tools

import (
	"context"
	"errors"
	"time"

	"gitee.com/EagleMao/eino_n9e_tool/pkg/httpx"
	"gitee.com/EagleMao/eino_n9e_tool/pkg/logger"
)

type N9EService struct {
	httpx *httpx.HttpClient
}

func NewN9EClient(baseUrl, token string) *N9EService {
	var headers = map[string]string{"X-User-Token": token}
	return &N9EService{
		httpx: httpx.NewHttpX(baseUrl).SetHeaders(headers),
	}
}

// N9EResponse 定义统一返回格式
type N9EResponse struct {
	Dat any    `json:"dat"`
	Err string `json:"err"`
}

type QueryResp struct {
	Status string                 `json:"status"`
	Data   map[string]interface{} `json:"data"`
}

// GetUserProfile 获取用户信息
func (cli *N9EService) GetUserProfile(_ context.Context) (*UserProfile, error) {
	var userProfile UserProfile
	err := cli.httpx.Request("GET", "/api/v1/user/profile", nil, &userProfile, nil)
	if err != nil {
		return nil, err
	}
	return &userProfile, nil
}

// GetCurrentEvent 获取当前告警事件
func (cli *N9EService) GetCurrentEvent(param CurrentEventParam) (*N9EResponse, error) {
	var resp N9EResponse
	err := cli.httpx.Request("GET", "/api/n9e/alert-cur-events/list", param, &resp, nil)
	if err != nil {
		return nil, err
	}
	return &resp, nil
}

// GetHistoryEvent 获取历史告警事件
func (cli *N9EService) GetHistoryEvent(param HistoryEventParam) (*N9EResponse, error) {
	var resp N9EResponse
	err := cli.httpx.Request("GET", "/api/n9e/alert-his-events/list", param, &resp, nil)
	if err != nil {
		return nil, err
	}
	return &resp, nil
}

func (cli *N9EService) GetMetrics(param MetricsQueryParam) (*QueryResp, error) {
	//
	// /api/n9e/proxy/1/api/v1/query_range?query=cpu_usage_active%7Bident%3D%22rc-es-178%22%7D&start=1762219807&end=1762223407&step=15
	if param.Query == "" {
		return nil, errors.New("缺少指标参数")
	}
	if param.Start == "" {
		logger.Info("设置查询的开始时间为当前时间前15分钟")
		param.Start = time.Duration(time.Now().Unix() - 15).String()
	}
	if param.End == "" {
		logger.Info("设置查询的结束时间为当前时间")
		param.End = time.Duration(time.Now().Unix()).String()
	}

	// 定义请求参数
	option := map[string]string{}

	if param.Ident != "" {
		option["ident"] = param.Ident
	}
	if param.Query != "" {
		option["query"] = param.Query
	}

	if param.Start != "" {
		option["start"] = param.Start
	}

	if param.End != "" {
		option["end"] = param.End
	}

	if param.Step != "" {
		option["step"] = param.Step
	}

	rq := &httpx.RequestOptions{
		QueryParams: option,
	}

	var resp QueryResp
	err := cli.httpx.Request("GET", "/api/n9e/proxy/1/api/v1/query_range", nil, &resp, rq)

	if err != nil {
		return nil, err
	}
	return &resp, nil

}
